<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Customer extends Auth_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('customer_mdl');
        $this->load->model('source_mdl');
        $this->load->model('custlog_mdl');
    }

    /**
     * 客户公海
     */
    public function common(){
        $this->db->where('user_id','-1');
        $list = $this->customer_mdl->select();
        $ctypes = $this->customer_mdl->ctype;
        $cranks = $this->customer_mdl->cranks;
        $this->db->select('id,title');
        $sources = $this->source_mdl->select();

        foreach($list as $k => $v){
            foreach($sources as $key => $value){
                if($v['source_id'] == $value['id']){
                    $list[$k]['source_name'] = $value['title'];
                    break;
                }
            }
        }

        $data = array('list'=>$list);
        $this->_view('common',$data);
    }

    /**
     * 查看客户历史
     */
    public function show_log(){
        $cid = $this->input->get('cid');
        if(empty($cid)){
            show_error('该客户不存在！');
        }
        $this->db->where('cust_id',$cid);
        $this->db->order_by('update_time desc');

        $list = $this->custlog_mdl->select();

        $this->load->model('users_mdl');

        foreach($list as $k => $v){
            $this->db->cache_on();
            $this->db->where('id',$v['user_id']);
            $this->db->select('id,name');
            $list[$k]['user'] = $this->users_mdl->get_one();
            $this->db->cache_off();
        }

        $this->load->view('default/customer/log',array(
            'list' => $list
        ));
    }
    /**
     * 客户列表
     * @return [type] [description]
     */
    public function index(){

        if($_SESSION['user']['group'] != 1){
            $this->db->where('user_id',$_SESSION['user']['id']);
        }else{
            //Model
            $this->load->model('users_mdl');

            $this->db->where('user_id !=','-1');
        }
        $list = $this->customer_mdl->select();

        $ctypes = $this->customer_mdl->ctype;
        $cranks = $this->customer_mdl->cranks;
        $this->db->select('id,title');
        $sources = $this->source_mdl->select();

        foreach($list as $k => $v){
            foreach($ctypes as $key => $value){
                if($v['ctype'] == $key){
                    $list[$k]['ctype_name'] = $value;
                    break;
                }
            }

            foreach($cranks as $key => $value){
                if($v['crank'] == $key){
                    $list[$k]['crank_name'] = $value;
                    break;
                }
            }

            foreach($sources as $key => $value){
                if($v['source_id'] == $value['id']){
                    $list[$k]['source_name'] = $value['title'];
                    break;
                }
            }

            if($_SESSION['user']['group'] == 1){
                $this->db->cache_on();
                $this->db->where('id',$v['user_id']);
                $this->db->select('id,name');
                $list[$k]['user'] = $this->users_mdl->get_one();
                $this->db->cache_off();
            }

            //最后更新时间
            $tmp_time = $_SERVER['REQUEST_TIME'] - $v['update_time'];

            if($tmp_time < 60){
                $tmp = $tmp_time.'秒前';
            }elseif($tmp_time < 60*60){
                $tmp = ceil($tmp_time/60)-1;
                $tmp .= '分钟前';
            }elseif($tmp_time < 60*60*24){
                $tmp = ceil($tmp_time/60/60)-1;
                $tmp .= '小时前';
            }elseif($tmp_time < 60*60*24*30){
                $tmp = ceil($tmp_time/60/60/24)-1;
                $tmp .= '天前';
            }elseif($tmp_time < 60*60*24*30*12){
                $tmp = ceil($tmp_time/60/60/24/30)-1;
                $tmp .= '月前';
            }else{
                $tmp = ceil($tmp_time/60/60/24/30/12)-1;
                $tmp .= '年前';
            }

            $list[$k]['update_date'] = $tmp;
        }

        $data = array('list'=>$list);
        $this->_view('index',$data);
    }

    /**
     * 修改客户
     */
    public function c_update(){
        if($this->input->is_ajax_request()){
            $post = $this->input->post();
            $cid = intval($post['cid']);
            $this->db->where('id',$cid);
            if($_SESSION['user']['group'] != 1){
                $this->db->where('user_id',$_SESSION['user']['id']);
            }else{
                $this->db->where('user_id','-1');
            }
            $this->db->select('id');
            $res = $this->customer_mdl->get_one();
            if(empty($res)){
                die('该客户不存在！');
            }

            if(!empty($post['email']) && !preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$post['email'])){
                die('请填写正确的邮箱格式');
            }

            if(empty($post['address'])){
                die('客户区域不能为空');
            }

            if(!preg_match("/^1[0-9]{10}$/",$post['phone'])){
                die('联系电话格式错误，请填写11位的手机号码');
            }

            //判断客户姓名和客户电话是唯一
            $this->db->where('id !=',$cid);
            $this->db->where('phone',$post['phone']);
            $this->db->select('id');
            $res = $this->customer_mdl->get_one();

            if(!empty($res)){
                die('该客户电话已存在数据库中，不能重复添加');
            }

            unset($post['cid']);
            $post['update_time'] = $_SERVER['REQUEST_TIME'];
            $this->db->where('id',$cid);
            $res = $this->customer_mdl->update($post);
            echo $res === TRUE ? '1' : '添加失败！';
        }else{
            $cid = $this->input->get('cid');

            if($_SESSION['user']['group'] != 1){
                $this->db->where('user_id',$_SESSION['user']['id']);
            }

            $this->db->where('id',$cid);
            $res = $this->customer_mdl->get_one();

            if(empty($res)){
                show_error('该客户不存在');
            }
            $source_list = $this->source_mdl->select();

            $data = array(
                'sou_list' => $source_list,
                'res' => $res,
                'ctype' => $this->customer_mdl->ctype,
                'cranks' => $this->customer_mdl->cranks
            );
            $this->_view('update',$data);
        }
    }

    /**
     * 客户数据导出
     */
    public function csv_result(){
        if($_SESSION['user']['group'] != 1){
            $this->db->where('user_id',$_SESSION['user']['id']);
        }
        //生成查询迭代
        $this->db->select('cname as "客户姓名",phone as "联系电话" ,address as "地区",ctype as "客户类型"');
        $sql = $this->db->get_compiled_select($this->customer_mdl->table);
        $this->load->dbutil();
        $query = $this->db->query($sql);

        $data = $this->dbutil->csv_from_result($query);
        //将内容写入文档中
        $this->load->helper('file');
        $file_name = $_SESSION['user']['id'].'.csv';
        write_file('./upload/'.$file_name, $data);
        redirect(base_url('upload/'.$file_name));
    }

    /**
     * 删除用户， 并放入公海中
     */
    public function c_delete(){
        if(!$this->input->is_ajax_request()){
            show_404();
        }

        $cid = $this->input->post("cid");

        $this->db->where('id',$cid);
        $this->db->set('user_id',-1);
        $this->db->set('update_time',$_SERVER['REQUEST_TIME']);
        $res = $this->customer_mdl->update();
        $this->custlog_mdl->action_add($cid,2);
        echo $res == true ? 1 : '删除失败！';

    }

    /**
     * 从公海中获取客户
     */
    public function c_retrieve(){
        if(!$this->input->is_ajax_request()){
            show_404();
        }

        $cid = $this->input->post("cid");

        $this->db->where('id',$cid);
        $this->db->where('user_id','-1');
        $this->db->set('user_id',$_SESSION['user']['id']);
        $this->db->set('update_time',$_SERVER['REQUEST_TIME']);
        $res = $this->customer_mdl->update();
        $this->custlog_mdl->action_add($cid);
        echo $res == true ? 1 : '获取客户失败！';
    }

    /**
     * 从公海中删除客户
     */
    public function r_delete(){
        if(!$this->input->is_ajax_request()){
            show_404();
        }

        if($_SESSION['user']['group'] != 1){
            die('没有权限删除公海数据');
        }

        $cid = $this->input->post("cid");

        //删除客户表数据
        $this->db->where('id',$cid);
        $this->db->where('user_id','-1');
        $this->customer_mdl->delete();
        //删除客户记录表数据
        $this->db->where('cust_id',$cid);
        $this->custlog_mdl->delete();

        echo 1;

    }

    /**
     * 添加客户
     */
    public function c_create(){
        if($this->input->is_ajax_request()){
            $post = $this->input->post();
            if(empty($post)){
                die('请提交相关数据');
            }

            if(empty($post['cname'])){
                die('客户姓名不能为空');
            }

            if(!preg_match("/^1[0-9]{10}$/",$post['phone'])){
                die('联系电话格式错误，请填写11位的手机号码');
            }

            if(!empty($post['email']) && !preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$post['email'])){
                die('请填写正确的邮箱格式');
            }

            if(empty($post['address'])){
                die('客户区域不能为空');
            }

            //判断客户姓名和客户电话是唯一
            $this->db->or_where('phone',$post['phone']);
            $this->db->select('id');
            $res = $this->customer_mdl->get_one();

            if(!empty($res)){
                die('该客户电话已存在数据库中，不能重复添加');
            }

            $post['user_id'] = $_SESSION['user']['id'];
            $post['create_time'] = $_SERVER['REQUEST_TIME'];
            $post['update_time'] = $_SERVER['REQUEST_TIME'];

            $r = $this->customer_mdl->create($post);
            $this->custlog_mdl->action_add($r);
            echo $r == true ? 1 : '添加失败！';
        }else{
            $source_list = $this->source_mdl->select();

            $data = array(
                'sou_list' => $source_list
            );
            $this->_view('create',$data);
        }
    }

}

/* End of file Customer.php */
/* Location: ./application/controllers/Customer.php */